package swingxrcp.framework.client.application;

import javax.swing.ImageIcon;
import javax.swing.SwingWorker;

import swingxrcp.framework.client.context.SwingXContext;
import swingxrcp.framework.client.swingx.JXFrame;
import swingxrcp.framework.client.swingx.JXSplash;
import swingxrcp.framework.client.swingx.PageAdvisor;
import swingxrcp.framework.model.domain.Config;
import swingxrcp.framework.util.StringUtils;
import swingxrcp.framework.util.log.Logger;
import swingxrcp.framework.util.log.LoggerFactory;

public class Console {
	/**
	 * 日志输出接口
	 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private JXSplash splash;

	private Config config;

	public Console(Config config) {
		this.config = config;
	}

	/**
	 * 运行启动界面
	 */
	public void startSplash() {
		splash = new JXSplash(new ImageIcon(config.getSplashIcon()), config.isSplashfadein());
		splash.startSplash();
		String[] infos = StringUtils.parse(config.getSplashInfo());
		for (String info : infos) {
			splash.setSplashInfos(info);
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
			}
		}

	}

	/**
	 * 关闭启动界面
	 */
	private void stopSplash() {
		splash.stopSplash();
	}

	/**
	 * 如果设置了主框架类返回真,启动应用程序
	 *
	 * @return boolean
	 */
	public boolean isStartup() {
		if (SwingXContext.MAIN_FRAME_CLASS
				.equals(" Not Define Main Window Class ")
				|| "".equals(SwingXContext.MAIN_FRAME_CLASS)) {
			return false;
		}
		return true;
	}

	public void run() {
		SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
			public Object doInBackground() {
				try {
					/** *** 创建主框架类对象 *** */
					PageAdvisor.showSplashInfo("创建主框架类对象...");
					Application.mainFrame = (JXFrame) Class.forName(SwingXContext.MAIN_FRAME_CLASS).newInstance();
				} catch (Exception e) {
					logger.error("Main Frame 类找不到,创建,打开失败. " + "当前Main Frame 类是'" + SwingXContext.MAIN_FRAME_CLASS + "'");
					System.exit(3);
				}
				return Application.mainFrame;
			}

			public void done() {
				if (config.isSplash()) {
					stopSplash();
				}
				Application.mainFrame.open();
			}
		};
		worker.execute();
	}

}
